;
(function(call) {
    var nwgdyb = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        router: {
            cfg: "/business/kgyb/json/nwgdyb.json",
            gridData: 'zhfx/gridKGYB/queryProvinceGridData',
            getLatestTime: 'zhfx/gridKGYB/queryProvinceGridData/LatestTime'
        },
        init: function() {
            var that = this;
            $.getJSON(that.router.cfg, function(cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
        },
        // 获取最新起报时间
        getLatestTime: function(call) {
            var that = this;
            var param = {
                element: 'TMP03'
            };
            $.ajax({
                url: this.router.getLatestTime,
                type: 'GET',
                dataType: 'json',
                data: param,
            }).done(function(res) {
                if (call)
                    call(res.data);
            })
        },
        buildContainer: function(data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function(item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function() {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");

                    $('.product-nwgdyb-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="nwgdybDate" data-options="${item.dateOptions}" value="">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-nwgdyb-datepicker .date-panel", {
                        query: function query() {
                            nwgdyb.buildLastTime(function() {
                                nwgdyb.getMultiGridData();
                            });
                        }
                    });
                    that.getLatestTime(function(latestTime){
                        if (latestTime)
                            $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().setVal(latestTime);
                        that.buildLastTime();
                        $(".product-nwgdyb-list").find('li.default').trigger('click');
                    });
                    that.buildLastTime();
                    that.buildProContent(data.basic_pro[item.id] || []);
                })
                $(".product-nwgdyb-tab ul").append($li);
            })
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function(data) {
            var that = this;
            $(".product-nwgdyb-list").empty();
            data.forEach(function(item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');

                $title.data('type', item.group_id);
                $title.html(item.group_name);

                $item.append($title);

                if (item.content) {
                    var $ul = $('<ul>');
                    item.content.forEach(function(pro) {
                        var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                        if (pro.selected)
                            $li.addClass("default");
                        $li.data('pro', pro);
                        if (pro.title)
                            $li.attr('title', pro.title);
                        if (pro.width)
                            $li.css("width", pro.width);
                        $ul.append($li);
                    })
                    $item.append($ul);
                }
                $(".product-nwgdyb-list").append($item);
            })
        },
        //点击显示pdf技术说明
        showTechPdf:function(id,path){
            var that = this;
            if (CafeJS.ModalBoxExist(id)) {
                CafeJS.ModalBoxShow(id);
                return;
            }
            CafeJS.ModalBox({
                id: id,
                container: 'cafe-busis-container',
                title: "技术说明",
                width: 1300,
                height: 700,
                m_top: 70,
                m_right: 90,
                hasMask:true,
                hide: true,
                html: "<div id='"+id+"' style='width:100%;height:calc(100% - 10px)'></div>",
                showCall: function(obj) {
                    PDFObject.embed(path,"#"+id);
                },
                closed: function () { }
            });
        },
        // 初始化最近起报时间
        buildLastTime: function(call) {
            var interval = $(".product-nwgdyb-tab li.active").data("model").interval;
            var baseDate = $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().getVal() + ":00";
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                newDate.setHours(newDate.getHours() - interval);
            }
            $(".product-nwgdyb-datechange ul").empty().append(liArr.reverse().join(""));

            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function(pro) {
            var that = this;
            var startTime = pro.time;

            var layers = that.getModels(pro.ele);
            var interval = pro.ele.interval ? pro.ele.interval*60 : 3*60;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                pro: pro,
                dateOpt: {
					dateFmt : 'yyyy-MM-dd hh',
                	timeInterval: 12,
                	customHm: [8,20]
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function(pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);

                    that.getModelGridData(pro);
                },
                getPlayData: function(pro, timeArr) {
                    that.getModelGridData(pro, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
        // 初始化图例
        initLegentpicker: function(ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [];
            $.each(layers, function(i, m) {
                layerIds.push(m.id);
            });
            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                seq: 'decrease',
                productId: ele.color_id,
                isShowSlider: true
            });
        },
        // 获取选中的要素格点数据
        getMultiGridData: function() {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function(pro) {
                var proInfo = that.getProInfo(pro);
                that.getModelGridData(proInfo);
            })
            var forecastTime = that.playList.getCurTime();
            var time = $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().getVal() + ":00";
            CafeJS.layerManage.updateLayerTime(time, 'nwgdyb', forecastTime);
        },
        getModelGridData: function(proInfo, timeArr) {
            var that = this;
            if (!proInfo) return;
            var pro = proInfo.ele;
            var element = pro.ele_id;
            var timeIndexs = 1;
            var queryTime = that.playList.getCurTime()+":00";
            var qbTime = proInfo.time+":00";
            var agings = [],
                aging;
            if (timeArr) {
                timeArr.split(',').forEach(function(i) {
                    aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    agings.push(aging / pro.interval);
                })
                agings = agings.join(',');
            } else {
                agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                agings = agings / pro.interval;
            }
            
            var params = {
                queryTime: qbTime,
                timeIndexs: agings - 1,
                element: element
            }
            CafeJS.ajax({
                url: that.router.gridData,
                params: params,
                type: "GET",
                success: function(e) {
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        // 绘制格点色斑图
        drawGridRawMap: function(data, pro) {
            var typeArr = this.getModels(pro);

            var colorObj = CafeJS.Legentconfig().cfg()[pro.color_id];

            // 显示色斑和数值
            GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
            CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
        },
        //获取要素样式
        getModels: function(pro) {
            var models = [];
            $.each(pro.models.split(","), function(i, m) {
                var layerId = "nwgdyb-layer-" + m + "-" + pro.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: false,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function(proInfo) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function(pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function(pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid && !proInfo.ele.frames) {
                that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
            }
        },
        // 删除图层后取消要素选择
        delLayer: function(pro) {
            var eleid = pro.ele.ele_id;
            if (pro.isGrid) {
                $(".product-nwgdyb-list li.active").each(function() {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })

                $(".product-nwgdyb-list td.active").each(function() {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })
            }

        },
        // 删除该模式所有的要素数据
        delAllLayer: function() {
            $(".product-nwgdyb-list li.active,.product-nwgdyb-list td.active").each(function() {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function(ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function(ele) {
            var height = ele.height != undefined ? ele.height : '';
            var name = $('.product-nwgdyb-tab li.active').data('model').name;
            name += '_' + height + ele.ele_name;
            var time = $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'nwgdyb',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function(ele_id) {
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function(layerId) {
                if (layerId.indexOf('nwgdyb-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function() {
            var that = this;
            // 要素点击事件
            $(".product-nwgdyb-list").off('click').on('click', 'li', function() {
                var pro = $(this).data('pro');
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);

                    that.clearGridLayer(pro.ele_id);
                    that.removeLayer(pro);
                } else {
                    $(this).siblings('li.active').click();
                    $(this).addClass("active");

                    if (pro.interval) {
                        $(".product-nwgdyb-interval li").addClass('disabled');
                        $(".product-nwgdyb-interval li[interval="+pro.interval+"]").addClass('active').removeClass('disabled').siblings().removeClass('active');
                    }

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);

                    that.getModelGridData(proInfo);
                }
            })
            // 预报时间间隔
            $(".product-nwgdyb-interval").delegate('li', 'click', function() {
                    if ($(this).hasClass('disabled')) return;
                    $(this).addClass("active").siblings().removeClass("active");
                    var interval = Number($(this).attr('interval')) * 60;

                    that.playList.init({
                        timeInterval: interval
                    });

                    that.getMultiGridData();
                })
            // 最近起报时间
            $(".product-nwgdyb-datechange").delegate('li', 'click', function() {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');

                $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().setVal(time);

                that.playList.init({
                    curDate: time
                });

                that.getMultiGridData();
            })
            $('.product-nwgdyb-datepicker').off('click').on('click', '.btn-forward', function(e) { // 日期向前
                e.stopPropagation();
                $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().toForward();
                that.buildLastTime(function() {
                    that.getMultiGridData();
                });
            }).on('click', '.btn-backward', function(e) { // 日期向后
                e.stopPropagation();
                $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().toBackward();
                that.buildLastTime(function() {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function(e) { // 最新
                e.stopPropagation();
                $(".product-nwgdyb-datepicker #nwgdybDate").IDatePicker().toNewest();
                that.buildLastTime(function() {
                    that.getMultiGridData();
                });
            });
            $(".product-nwgdyb-tab li").first().click();
        }
    }
    if (typeof call === 'function') {
        CafeJS.nwgdyb = nwgdyb;
        call(nwgdyb);
    }
    window.nwgdyb = nwgdyb;
})(function(nwgdyb) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function() {
        nwgdyb.init();
    });
});
